//
//  CommonMethod.m
//  SameWorld
//
//  Created by 李小朋 on 2017/3/29
//  Copyright © 2017年 杨旭. All rights reserved.
//

#import "CommonMethod.h"
#import <sys/socket.h>
#import <sys/sockio.h>
#import <sys/ioctl.h>
#import <net/if.h>
#import <arpa/inet.h>


@implementation CommonMethod
//验证是否整数
+ (BOOL)validateNum:(NSString *)textString{
    
    NSString * myphone = @"^\\+?[0-9][0-9]*$";
    NSPredicate *regextestmyphone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myphone];
    if ([regextestmyphone evaluateWithObject:textString] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//验证是否两位小数
+ (BOOL)validateTwoDecimal:(NSString *)textString
{
    NSString * myphone = @"^[0-9]+([.][0-9]{0,2})?$";
    NSPredicate *regextestmyphone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myphone];
    if ([regextestmyphone evaluateWithObject:textString] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//通过正则表达式验证手机号
+ (BOOL)validatePhone:(NSString *)textString{
    //    NSString *phone = @"^1[43578]\\d{9}$";
    //    NSPredicate *phonePre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phone];
    //    return [phonePre evaluateWithObject:textString];
    
    NSString * myphone = @"^1\\d{10}$";
    NSPredicate *regextestmyphone = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", myphone];
    if ([regextestmyphone evaluateWithObject:textString] == YES)
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

//隐藏手机号码的中间四位
+(NSString *)handlePhoneNumber:(NSString *)number
{
    NSString *first = @"";
    NSString *last = @"";
    if (number != nil)
    {
        first = [[number substringFromIndex:0]substringToIndex:3];
        last = [[number substringFromIndex:7]substringToIndex:4];
        number = [NSString stringWithFormat:@"%@****%@",first,last];
    }
    return number;
}


//通过正则表达式验证邮箱
+ (BOOL)validateEamil:(NSString*)emailString{
    
    NSString *regex = @"^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:emailString];
}

//函数功能：字符串判空
+(BOOL)checkStrEmpty:(NSString *) parmStr
{
    if (!parmStr) {
        return YES;
    }
    if ([parmStr isEqual:nil]) {
        return YES;
    }
    if ([parmStr isEqual:@""]) {
        return YES;
    }
    id tempStr=parmStr;
    if (tempStr==[NSNull null]) {
        return YES;
    }
    return NO;
}

+ (NSDate*)getDateNow
{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    return localeDate;
}

+ (NSString*)getDateNow:(NSString *)formatterString{
    
    NSDate *nowDate = [NSDate date];
    
    NSDateFormatter *format = [[NSDateFormatter alloc]init];
    
    format.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [format setDateFormat:formatterString];
    NSString *dateStr = [format stringFromDate:nowDate];
    
    return dateStr;
}

//根据字符串获得自适应的Size
+ (CGSize)getSizeWithStr:(NSString *)str width:(CGFloat)width attributes:(NSDictionary *)attributesDics{
    
    if (attributesDics ==nil) {//如果不设置字号，默认为17号
        NSMutableDictionary *attributesDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:17], NSFontAttributeName, nil];
        
        if ([attributesDics objectForKey: NSParagraphStyleAttributeName] == nil) {//如果不设置间距，则间距默认为0
            NSMutableParagraphStyle * paragraphStyles = [[NSMutableParagraphStyle alloc] init];
            [paragraphStyles setLineSpacing:0];
            [attributesDic setObject:paragraphStyles forKey:NSParagraphStyleAttributeName];
            
        }
        
        //计算整体高度
        CGSize allSize = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDic context:nil].size;
        
        //计算当行高度
        CGSize singleSize = [str sizeWithAttributes:attributesDic];
        
        //如果相等，证明为单行，需要把行间距去掉，防止出现单行，下面扔出现行间距的情况
        if (allSize.height == singleSize.height) {
            [[attributesDics objectForKey: NSParagraphStyleAttributeName] setLineSpacing:0];
        }
        
        CGSize size = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributesDic context:nil].size;
        
        return size;
    }
    
    
    //计算整体高度
    CGSize allSize = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attributesDics context:nil].size;
    
    //计算当行高度
    CGSize singleSize = [str sizeWithAttributes:attributesDics];
    
    //如果相等，证明为单行，需要把行间距去掉，防止出现单行，下面扔出现行间距的情况
    if (allSize.height == singleSize.height) {
        [[attributesDics objectForKey: NSParagraphStyleAttributeName] setLineSpacing:0];
    }
    
    CGSize size = [str boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:attributesDics context:nil].size;
    
    return size;
}

//播放声音
+ (void)playCustomSound:(NSString *)soundPath{
    static SystemSoundID shake_sound_male_id = 0;
    
    if (soundPath) {
        //注册声音到系统
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundPath],&shake_sound_male_id);
        AudioServicesPlaySystemSound(shake_sound_male_id);
        //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
    }
    
    AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
    
    //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
}

//图片旋转回正常
+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

//显示黑色等待弹窗
+ (MBProgressHUD*)openHUD:(NSString*)message
{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithWindow:[CommonMethod getAppDelegate].window];
    [[CommonMethod getAppDelegate].window addSubview:HUD];
    HUD.labelText = message;
    HUD.mode = MBProgressHUDModeIndeterminate;
    HUD.yOffset = -50.0f;
    [HUD show:YES];
    return HUD;
}

//关闭弹窗
+ (void)closeHUD:(MBProgressHUD*)HUD
{
    [HUD hide:YES];
    [HUD removeFromSuperview];
    HUD = nil;
}

+ (AppDelegate *) getAppDelegate {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

+ (NSString *)returnFormatString:(NSString *)str
{
    return [str stringByReplacingOccurrencesOfString:@" "withString:@""];
}

+(NSString*)timeStringForTimeInterval:(NSTimeInterval)timeInterval
{
    NSInteger ti = (NSInteger)timeInterval;
    NSInteger seconds = ti % 60;
    NSInteger minutes = (ti / 60) % 60;
    NSInteger hours = (ti / 3600);
    
    if (hours > 0)
    {
        return [NSString stringWithFormat:@"%02li:%02li:%02li", (long)hours, (long)minutes, (long)seconds];
    }
    else
    {
        return  [NSString stringWithFormat:@"%02li:%02li", (long)minutes, (long)seconds];
    }
}

/*
 **播放声音
 */
-(void)playCustomSound:(NSString *)soundPath{
    static SystemSoundID shake_sound_male_id = 0;
    
    if (soundPath) {
        //注册声音到系统
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundPath],&shake_sound_male_id);
        AudioServicesPlaySystemSound(shake_sound_male_id);
        //        AudioServicesPlaySystemSound(shake_sound_male_id);//如果无法再下面播放，可以尝试在此播放
    }
    
    AudioServicesPlaySystemSound(shake_sound_male_id);   //播放注册的声音，（此句代码，可以在本类中的任意位置调用，不限于本方法中）
    
    //    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);   //让手机震动
}

+ (NSString *)getDeviceIPIpAddresses {
    
    int sockfd =socket(AF_INET,SOCK_DGRAM, 0);
    
    //    if (sockfd <</span> 0) return nil;
    
    NSMutableArray *ips = [NSMutableArray array];

    
    int BUFFERSIZE =4096;
    
    struct ifconf ifc;
    
    char buffer[BUFFERSIZE], *ptr, lastname[IFNAMSIZ], *cptr;
    
    struct ifreq *ifr, ifrcopy;
    
    ifc.ifc_len = BUFFERSIZE;
    
    ifc.ifc_buf = buffer;
    
    if (ioctl(sockfd,SIOCGIFCONF, &ifc) >= 0){
        
        for (ptr = buffer; ptr < buffer + ifc.ifc_len; ){
            
            ifr = (struct ifreq *)ptr;
            
            int len =sizeof(struct sockaddr);
            
            if (ifr->ifr_addr.sa_len > len) {
                
                len = ifr->ifr_addr.sa_len;
                
            }
            
            ptr += sizeof(ifr->ifr_name) + len;
            
            if (ifr->ifr_addr.sa_family !=AF_INET) continue;
            
            if ((cptr = (char *)strchr(ifr->ifr_name,':')) != NULL) *cptr =0;
            
            if (strncmp(lastname, ifr->ifr_name,IFNAMSIZ) == 0)continue;
            
            memcpy(lastname, ifr->ifr_name,IFNAMSIZ);
            
            ifrcopy = *ifr;
            
            ioctl(sockfd,SIOCGIFFLAGS, &ifrcopy);
            
            if ((ifrcopy.ifr_flags &IFF_UP) == 0)continue;
            
            
            
            NSString *ip = [NSString stringWithFormat:@"%s",inet_ntoa(((struct sockaddr_in *)&ifr->ifr_addr)->sin_addr)];
            
            [ips addObject:ip];
        }
    }
    
    close(sockfd);
    
    NSString *deviceIP =@"";
    
    for (int i=0; i < ips.count; i++) {
        
        if (ips.count >0) {
            deviceIP = [NSString stringWithFormat:@"%@",ips.lastObject];
            
        }
    }
    
    NSLog(@"deviceIP========%@",deviceIP);
    return deviceIP;
}

@end
